<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';

const router = useRouter();

// 安防设备数据
const securityDevices = ref([
  {
    id: '1',
    name: '摄像头-大厅',
    deviceId: 'CAM001',
    type: 'camera',
    status: 'online',
    location: '1号楼大厅',
    lastUpdate: '2024-01-19 15:30:00',
    recording: true,
    motionDetection: true,
    nightVision: true,
    resolution: '1080p',
    battery: 95,
    signal: 92,
    storage: 85,
  },
  {
    id: '2',
    name: '门禁系统-前台',
    deviceId: 'ACCESS001',
    type: 'access_control',
    status: 'online',
    location: '前台',
    lastUpdate: '2024-01-19 15:30:00',
    accessMode: 'normal',
    emergencyMode: false,
    lastAccess: '2024-01-19 15:25:00',
    accessUser: '张三',
    battery: 88,
    signal: 85,
  },
  {
    id: '3',
    name: '烟雾报警器-餐厅',
    deviceId: 'SMOKE001',
    type: 'smoke_alarm',
    status: 'warning',
    location: '1号楼餐厅',
    lastUpdate: '2024-01-19 15:25:00',
    smokeLevel: 15,
    threshold: 10,
    alarmStatus: 'active',
    battery: 45,
    signal: 65,
  },
  {
    id: '4',
    name: '红外探测器-走廊',
    deviceId: 'IR001',
    type: 'motion_sensor',
    status: 'online',
    location: '1号楼走廊',
    lastUpdate: '2024-01-19 15:28:00',
    motionDetected: true,
    sensitivity: 'medium',
    detectionRange: '10m',
    battery: 78,
    signal: 75,
  },
  {
    id: '5',
    name: '对讲系统-监控室',
    deviceId: 'INTERCOM001',
    type: 'intercom',
    status: 'online',
    location: '监控室',
    lastUpdate: '2024-01-19 15:30:00',
    callStatus: 'idle',
    volume: 80,
    lastCall: '2024-01-19 15:20:00',
    battery: 92,
    signal: 90,
  },
]);

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: '',
  location: '',
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
});

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colors = {
    online: 'green',
    offline: 'red',
    warning: 'orange',
    error: 'red',
  };
  return colors[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const texts = {
    online: '在线',
    offline: '离线',
    warning: '异常',
    error: '故障',
  };
  return texts[status] || status;
};

// 获取设备类型文本
const getDeviceTypeText = (type: string) => {
  const types = {
    camera: '摄像头',
    access_control: '门禁系统',
    smoke_alarm: '烟雾报警器',
    motion_sensor: '红外探测器',
    intercom: '对讲系统',
    alarm_panel: '报警主机',
    cctv: '监控系统',
  };
  return types[type] || type;
};

// 获取电池颜色
const getBatteryColor = (battery: number) => {
  return battery > 60 ? 'green' : battery > 30 ? 'orange' : 'red';
  battery60;
};

// 获取信号颜色
const getSignalColor = (signal: number) => {
  return signal >= 80
    ? 'green'
    : signal >= 60
      ? 'blue'
      : signal >= 40
        ? 'orange'
        : 'red';
};

// 表格列定义
const columns = [
  {
    title: '设备名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
  },
  {
    title: '设备类型',
    dataIndex: 'type',
    key: 'type',
    width: 120,
  },
  {
    title: '设备状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '安装位置',
    dataIndex: 'location',
    key: 'location',
    width: 150,
  },
  {
    title: '当前状态',
    key: 'currentStatus',
    width: 120,
  },
  {
    title: '电池电量',
    dataIndex: 'battery',
    key: 'battery',
    width: 100,
  },
  {
    title: '信号强度',
    dataIndex: 'signal',
    key: 'signal',
    width: 100,
  },
  {
    title: '最后更新',
    dataIndex: 'lastUpdate',
    key: 'lastUpdate',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right' as const,
  },
];

// 过滤后的数据
const filteredDevices = computed(() => {
  let result = securityDevices.value;

  if (searchForm.name) {
    result = result.filter((item) =>
      item.name.toLowerCase().includes(searchForm.name.toLowerCase()),
    );
  }

  if (searchForm.type) {
    result = result.filter((item) => item.type === searchForm.type);
  }

  if (searchForm.status) {
    result = result.filter((item) => item.status === searchForm.status);
  }

  if (searchForm.location) {
    result = result.filter((item) =>
      item.location.toLowerCase().includes(searchForm.location.toLowerCase()),
    );
  }

  return result;
});

// 安防设备统计
const securityStatistics = computed(() => {
  const total = securityDevices.value.length;
  const online = securityDevices.value.filter(
    (s) => s.status === 'online',
  ).length;
  const warning = securityDevices.value.filter(
    (s) => s.status === 'warning',
  ).length;
  const offline = securityDevices.value.filter(
    (s) => s.status === 'offline',
  ).length;

  // 按类型统计
  const typeStats = securityDevices.value.reduce(
    (acc, device) => {
      acc[device.type] = (acc[device.type] || 0) + 1;
      return acc;
    },
    {} as Record<string, number>,
  );

  // 告警设备数
  const alarmDevices = securityDevices.value.filter((device) => {
    if (device.type === 'smoke_alarm' && device.alarmStatus === 'active')
      return true;
    if (device.type === 'motion_sensor' && device.motionDetected) return true;
    return false;
  }).length;

  return { total, online, warning, offline, typeStats, alarmDevices };
});

// 查看设备详情
const viewDevice = (record: any) => {
  router.push(`/hotel/iot-devices/detail/${record.id}`);
};

// 控制设备
const controlDevice = (record: any) => {
  Modal.info({
    title: `设备控制 - ${record.name}`,
    width: 800,
    content: '设备控制功能开发中...',
  });
};

// 配置设备
const configureDevice = (record: any) => {
  Modal.info({
    title: `设备配置 - ${record.name}`,
    width: 600,
    content: '安防设备配置功能开发中...',
  });
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  message.success('搜索完成');
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: '',
    location: '',
  });
  pagination.current = 1;
  message.success('重置完成');
};

onMounted(() => {
  pagination.total = filteredDevices.value.length;
});
</script>

<template>
  <div class="security-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>安防设备管理</h2>
      <Space>
        <Button @click="router.push('/hotel/iot-devices')">
          <IconifyIcon icon="ant-design:arrow-left-outlined" />
          返回设备列表
        </Button>
        <Button type="primary">
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加设备
        </Button>
      </Space>
    </div>

    <!-- 统计信息 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number total">{{ securityStatistics.total }}</div>
            <div class="stat-label">设备总数</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number online">
              {{ securityStatistics.online }}
            </div>
            <div class="stat-label">在线设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number warning">
              {{ securityStatistics.warning }}
            </div>
            <div class="stat-label">异常设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number offline">
              {{ securityStatistics.offline }}
            </div>
            <div class="stat-label">离线设备</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">
              {{
                securityStatistics.total > 0
                  ? Math.round(
                      (securityStatistics.online / securityStatistics.total) *
                        100,
                    )
                  : 0
              }}%
            </div>
            <div class="stat-label">在线率</div>
          </div>
        </Card>
      </Col>
      <Col :span="4">
        <Card class="stat-card">
          <div class="stat-content">
            <div class="stat-number">
              {{ securityStatistics.alarmDevices }}
            </div>
            <div class="stat-label">告警设备</div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 搜索表单 -->
    <Card class="search-card">
      <Form layout="inline" :model="searchForm" class="search-form">
        <Form.Item label="设备名称">
          <Input
            v-model:value="searchForm.name"
            placeholder="请输入设备名称"
            allow-clear
          />
        </Form.Item>
        <Form.Item label="设备类型">
          <Select
            v-model:value="searchForm.type"
            placeholder="请选择类型"
            allow-clear
            style="width: 120px"
          >
            <Select.Option value="camera">摄像头</Select.Option>
            <Select.Option value="access_control">门禁系统</Select.Option>
            <Select.Option value="smoke_alarm">烟雾报警器</Select.Option>
            <Select.Option value="motion_sensor">红外探测器</Select.Option>
            <Select.Option value="intercom">对讲系统</Select.Option>
            <Select.Option value="alarm_panel">报警主机</Select.Option>
            <Select.Option value="cctv">监控系统</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="设备状态">
          <Select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          >
            <Select.Option value="online">在线</Select.Option>
            <Select.Option value="offline">离线</Select.Option>
            <Select.Option value="warning">异常</Select.Option>
            <Select.Option value="error">故障</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="安装位置">
          <Input
            v-model:value="searchForm.location"
            placeholder="请输入安装位置"
            allow-clear
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" @click="handleSearch">
              <IconifyIcon icon="ant-design:search-outlined" />
              搜索
            </Button>
            <Button @click="handleReset">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>

    <!-- 设备列表 -->
    <Card title="安防设备列表" class="list-card">
      <Table
        :columns="columns"
        :data-source="filteredDevices"
        :pagination="pagination"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            {{ getDeviceTypeText(record.type) }}
          </template>
          <template v-else-if="column.key === 'status'">
            <Tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'currentStatus'">
            <div v-if="record.type === 'camera'">
              <div>录制: {{ record.recording ? '开启' : '关闭' }}</div>
              <div>分辨率: {{ record.resolution }}</div>
            </div>
            <div v-else-if="record.type === 'access_control'">
              <div>模式: {{ record.accessMode }}</div>
              <div>紧急: {{ record.emergencyMode ? '是' : '否' }}</div>
            </div>
            <div v-else-if="record.type === 'smoke_alarm'">
              <div>烟雾: {{ record.smokeLevel }} ppm</div>
              <div>告警: {{ record.alarmStatus }}</div>
            </div>
            <div v-else-if="record.type === 'motion_sensor'">
              <div>检测: {{ record.motionDetected ? '有活动' : '无活动' }}</div>
              <div>范围: {{ record.detectionRange }}</div>
            </div>
            <div v-else-if="record.type === 'intercom'">
              <div>状态: {{ record.callStatus }}</div>
              <div>音量: {{ record.volume }}%</div>
            </div>
            <div v-else>-</div>
          </template>
          <template v-else-if="column.key === 'battery'">
            <Tag :color="getBatteryColor(record.battery)">
              {{ record.battery }}%
            </Tag>
          </template>
          <template v-else-if="column.key === 'signal'">
            <Tag :color="getSignalColor(record.signal)">
              {{ record.signal }}%
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button type="link" size="small" @click="viewDevice(record)">
                查看
              </Button>
              <Button type="link" size="small" @click="controlDevice(record)">
                控制
              </Button>
              <Button type="link" size="small" @click="configureDevice(record)">
                配置
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>
  </div>
</template>

<style scoped>
.security-management {
  padding: 24px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.statistics-row {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 16px;
}

.stat-number {
  margin-bottom: 8px;
  font-size: 24px;
  font-weight: bold;
}

.stat-number.total {
  color: #1890ff;
}

.stat-number.online {
  color: #52c41a;
}

.stat-number.warning {
  color: #faad14;
}

.stat-number.offline {
  color: #f5222d;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.search-card {
  margin-bottom: 24px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.list-card {
  background: white;
}

:deep(.ant-card-body) {
  padding: 16px;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 500;
  background-color: #fafafa;
}
</style>
